<template>
  <div class="process-list-container">
    <!-- 顶部工具栏 -->
    <div class="toolbar">
      <div class="toolbar-left">
        <h2 class="page-title">审批流程管理</h2>
        <span class="process-count">共 {{ processList.length }} 个流程</span>
      </div>
      <div class="toolbar-right">
        <el-radio-group v-model="viewMode" size="small" style="margin-right: 16px;">
          <el-radio-button label="category">
            <i class="el-icon-menu"></i> 分类视图
          </el-radio-button>
          <el-radio-button label="list">
            <i class="el-icon-s-grid"></i> 列表视图
          </el-radio-button>
        </el-radio-group>
        <el-button type="primary" icon="el-icon-plus" @click="createProcess">创建流程</el-button>
      </div>
    </div>

    <!-- 分类卡片视图 -->
    <div v-if="viewMode === 'category'" class="category-view">
      <div 
        v-for="category in categories" 
        :key="category.value"
        class="category-section"
      >
        <div class="category-header">
          <div class="category-title">
            <i :class="category.icon" :style="{ color: category.color }"></i>
            <span class="category-name">{{ category.label }}</span>
            <el-badge :value="getCategoryProcessCount(category.value)" class="category-badge" />
          </div>
          <el-button 
            type="text" 
            size="small"
            @click="createProcessWithCategory(category.value)"
          >
            <i class="el-icon-plus"></i> 新建{{ category.label }}
          </el-button>
        </div>

        <div class="process-cards">
          <div 
            v-for="process in getCategoryProcesses(category.value)" 
            :key="process.id"
            class="process-card"
            @click="viewProcess(process)"
          >
            <div class="card-header">
              <div class="card-title">
                <i :class="process.icon || 'el-icon-document'" class="process-icon"></i>
                <span class="process-name">{{ process.processName }}</span>
                <el-tag v-if="process.version" type="info" size="mini" class="version-tag">
                  v{{ process.version }}
                </el-tag>
              </div>
              <div class="card-tags">
                <el-tag 
                  :type="process.status === 1 ? 'success' : 'info'" 
                  size="mini"
                >
                  {{ process.status === 1 ? '启用' : '禁用' }}
                </el-tag>
                <el-tag v-if="process.isNewVersion" type="warning" size="mini">
                  最新版本
                </el-tag>
              </div>
            </div>

            <div class="card-content">
              <p class="process-description">
                {{ process.description || '暂无描述' }}
              </p>
            </div>

            <div class="card-footer">
              <div class="footer-info">
                <span class="info-item">
                  <i class="el-icon-user"></i>
                  {{ process.creatorName || '未知' }}
                </span>
                <span class="info-item">
                  <i class="el-icon-time"></i>
                  {{ formatDate(process.createTime) }}
                </span>
              </div>
              <div class="footer-actions" @click.stop>
                <el-button 
                  type="text" 
                  size="mini" 
                  icon="el-icon-edit"
                  @click="editProcess(process)"
                >编辑</el-button>
                <el-button 
                  type="text" 
                  size="mini" 
                  icon="el-icon-time"
                  @click="viewProcessHistory(process)"
                >历史版本</el-button>
                <el-button 
                  type="text" 
                  size="mini" 
                  icon="el-icon-delete"
                  style="color: #F56C6C;"
                  @click="deleteProcess(process)"
                >删除</el-button>
              </div>
            </div>
          </div>

          <!-- 空状态 -->
          <div v-if="getCategoryProcessCount(category.value) === 0" class="empty-category">
            <i class="el-icon-document-add"></i>
            <p>暂无{{ category.label }}流程</p>
            <el-button 
              type="text" 
              size="small"
              @click="createProcessWithCategory(category.value)"
            >
              <i class="el-icon-plus"></i> 立即创建
            </el-button>
          </div>
        </div>
      </div>
    </div>

    <!-- 列表视图 -->
    <div v-else class="list-view">
      <el-table :data="processList" style="width: 100%">
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="processName" label="流程名称" min-width="150">
          <template slot-scope="scope">
            <span>{{ scope.row.processName }}</span>
            <el-tag v-if="scope.row.version && scope.row.version > 1" type="info" size="mini" style="margin-left: 8px;">
              v{{ scope.row.version }}
            </el-tag>
            <el-tag v-if="scope.row.isNewVersion" type="warning" size="mini" style="margin-left: 4px;">
              最新
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="category" label="分类" width="120">
          <template slot-scope="scope">
            <el-tag size="small" :color="getCategoryColor(scope.row.category)">
              {{ getCategoryLabel(scope.row.category) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="description" label="描述" show-overflow-tooltip min-width="200" />
        <el-table-column prop="status" label="状态" width="100">
          <template slot-scope="scope">
            <el-tag :type="scope.row.status === 1 ? 'success' : 'info'" size="small">
              {{ scope.row.status === 1 ? '启用' : '禁用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="creatorName" label="创建人" width="120" />
        <el-table-column prop="createTime" label="创建时间" width="180">
          <template slot-scope="scope">
            {{ formatDate(scope.row.createTime) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="240" fixed="right">
          <template slot-scope="scope">
            <el-button type="text" size="small" @click="editProcess(scope.row)">编辑</el-button>
            <el-button type="text" size="small" @click="viewProcess(scope.row)">查看</el-button>
            <el-button type="text" size="small" @click="viewProcessHistory(scope.row)">历史版本</el-button>
            <el-button 
              type="text" 
              size="small"
              style="color: #F56C6C;" 
              @click="deleteProcess(scope.row)"
            >删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 全局空状态 -->
    <div v-if="processList.length === 0" class="global-empty">
      <i class="el-icon-document"></i>
      <p class="empty-title">还没有创建任何流程</p>
      <p class="empty-description">点击下方按钮创建您的第一个审批流程</p>
      <el-button type="primary" icon="el-icon-plus" @click="createProcess">创建流程</el-button>
    </div>

    <!-- 历史版本对话框 -->
    <el-dialog
      title="流程历史版本"
      :visible.sync="historyDialogVisible"
      width="80%"
      :close-on-click-modal="false"
    >
      <div v-if="historyLoading" class="loading-container">
        <i class="el-icon-loading"></i>
        <span>加载中...</span>
      </div>
      
      <div v-else-if="historyVersions.length === 0" class="empty-history">
        <i class="el-icon-time"></i>
        <p>暂无历史版本</p>
      </div>
      
      <div v-else class="history-content">
        <div class="history-header">
          <h3>{{ currentProcess.processName }}</h3>
          <p class="process-key">流程Key: {{ currentProcess.processKey }}</p>
        </div>
        
        <el-table :data="historyVersions" stripe>
          <el-table-column prop="version" label="版本" width="80">
            <template slot-scope="scope">
              <el-tag :type="scope.row.isNewVersion ? 'warning' : 'info'" size="mini">
                v{{ scope.row.version }}
              </el-tag>
            </template>
          </el-table-column>
          
          <el-table-column prop="isNewVersion" label="状态" width="100">
            <template slot-scope="scope">
              <el-tag v-if="scope.row.isNewVersion" type="success" size="mini">
                最新版本
              </el-tag>
              <el-tag v-else type="info" size="mini">
                历史版本
              </el-tag>
            </template>
          </el-table-column>
          
          <el-table-column prop="description" label="描述" min-width="200">
            <template slot-scope="scope">
              {{ scope.row.description || '暂无描述' }}
            </template>
          </el-table-column>
          
          <el-table-column prop="creatorName" label="创建人" width="120">
            <template slot-scope="scope">
              {{ scope.row.creatorName || '未知' }}
            </template>
          </el-table-column>
          
          <el-table-column prop="createTime" label="创建时间" width="180">
            <template slot-scope="scope">
              {{ formatDate(scope.row.createTime) }}
            </template>
          </el-table-column>
          
          <el-table-column label="操作" width="150">
            <template slot-scope="scope">
              <el-button 
                type="text" 
                size="mini" 
                @click="viewVersionDetail(scope.row)"
              >查看详情</el-button>
              <el-button 
                v-if="!scope.row.isNewVersion"
                type="text" 
                size="mini" 
                @click="compareWithCurrent(scope.row)"
              >对比当前</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
      
      <div slot="footer" class="dialog-footer">
        <el-button @click="historyDialogVisible = false">关闭</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getProcessList, deleteProcess, getProcessHistory } from '@/api/process'

export default {
  name: 'ProcessList',
  
  data() {
    return {
      processList: [],
      viewMode: 'category', // category: 分类视图, list: 列表视图
      
      // 历史版本相关
      historyDialogVisible: false,
      historyLoading: false,
      historyVersions: [],
      currentProcess: {},
      
      // 审批分类配置
      categories: [
        {
          value: 'leave',
          label: '请假申请',
          icon: 'el-icon-s-check',
          color: '#409EFF',
          description: '员工请假审批流程'
        },
        {
          value: 'reimbursement',
          label: '报销申请',
          icon: 'el-icon-money',
          color: '#67C23A',
          description: '费用报销审批流程'
        },
        {
          value: 'purchase',
          label: '采购申请',
          icon: 'el-icon-shopping-cart-2',
          color: '#E6A23C',
          description: '物资采购审批流程'
        },
        {
          value: 'other',
          label: '其他流程',
          icon: 'el-icon-document',
          color: '#909399',
          description: '其他类型审批流程'
        }
      ]
    }
  },
  
  created() {
    this.loadProcessList()
    // 从本地存储恢复视图模式
    const savedViewMode = localStorage.getItem('processViewMode')
    if (savedViewMode) {
      this.viewMode = savedViewMode
    }
  },
  
  watch: {
    viewMode(newVal) {
      // 保存视图模式到本地存储
      localStorage.setItem('processViewMode', newVal)
    }
  },
  
  methods: {
    loadProcessList() {
      getProcessList()
        .then(res => {
          this.processList = res.data || []
        })
        .catch(error => {
          console.error('加载流程列表失败:', error)
          // 错误已在 request.js 中统一处理
        })
    },
    
    createProcess() {
      this.$router.push('/process/create')
    },
    
    // 创建指定分类的流程
    createProcessWithCategory(category) {
      this.$router.push({
        path: '/process/create',
        query: { category }
      })
    },
    
    editProcess(row) {
      this.$router.push(`/process/edit/${row.id}`)
    },
    
    viewProcess(row) {
      this.$router.push(`/process/edit/${row.id}`)
    },
    
    deleteProcess(row) {
      this.$confirm(`确定要删除流程"${row.processName}"吗？`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deleteProcess(row.id)
          .then(() => {
            this.$message.success('删除成功')
            this.loadProcessList()
          })
          .catch(error => {
            console.error('删除流程失败:', error)
            // 错误已在 request.js 中统一处理
          })
      }).catch(() => {
        // 用户取消删除
      })
    },
    
    // 获取指定分类的流程列表
    getCategoryProcesses(category) {
      return this.processList.filter(p => p.category === category)
    },
    
    // 获取指定分类的流程数量
    getCategoryProcessCount(category) {
      return this.getCategoryProcesses(category).length
    },
    
    // 获取分类标签
    getCategoryLabel(categoryValue) {
      const category = this.categories.find(c => c.value === categoryValue)
      return category ? category.label : categoryValue
    },
    
    // 获取分类颜色
    getCategoryColor(categoryValue) {
      const category = this.categories.find(c => c.value === categoryValue)
      return category ? category.color : '#909399'
    },
    
    formatDate(date) {
      if (!date) return '未知'
      const d = new Date(date)
      const year = d.getFullYear()
      const month = String(d.getMonth() + 1).padStart(2, '0')
      const day = String(d.getDate()).padStart(2, '0')
      return `${year}-${month}-${day}`
    },
    
    // 查看流程历史版本
    viewProcessHistory(process) {
      this.currentProcess = process
      this.historyDialogVisible = true
      this.loadProcessHistory(process.processKey)
    },
    
    // 加载流程历史版本
    loadProcessHistory(processKey) {
      this.historyLoading = true
      getProcessHistory(processKey)
        .then(res => {
          this.historyVersions = res.data || []
        })
        .catch(error => {
          console.error('加载历史版本失败:', error)
          this.$message.error('加载历史版本失败')
        })
        .finally(() => {
          this.historyLoading = false
        })
    },
    
    // 查看版本详情
    viewVersionDetail(version) {
      this.$router.push(`/process/edit/${version.id}`)
    },
    
    // 对比当前版本
    compareWithCurrent(version) {
      this.$message.info('版本对比功能开发中...')
      // TODO: 实现版本对比功能
    }
  }
}
</script>

<style scoped>
.process-list-container {
  background: #f5f7fa;
  padding: 20px;
  min-height: calc(100vh - 100px);
}

/* 工具栏 */
.toolbar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
  padding: 20px;
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
}

.toolbar-left {
  display: flex;
  align-items: center;
  gap: 16px;
}

.page-title {
  margin: 0;
  font-size: 20px;
  font-weight: 600;
  color: #303133;
}

.process-count {
  padding: 4px 12px;
  background: #f0f2f5;
  border-radius: 12px;
  font-size: 13px;
  color: #606266;
}

.toolbar-right {
  display: flex;
  align-items: center;
}

/* 分类视图 */
.category-view {
  display: flex;
  flex-direction: column;
  gap: 24px;
}

.category-section {
  background: #fff;
  border-radius: 8px;
  padding: 20px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
}

.category-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding-bottom: 16px;
  border-bottom: 2px solid #f0f2f5;
}

.category-title {
  display: flex;
  align-items: center;
  gap: 12px;
}

.category-title i {
  font-size: 24px;
}

.category-name {
  font-size: 18px;
  font-weight: 600;
  color: #303133;
}

.category-badge {
  margin-left: 8px;
}

/* 流程卡片 */
.process-cards {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(320px, 1fr));
  gap: 16px;
}

.process-card {
  border: 1px solid #e4e7ed;
  border-radius: 8px;
  padding: 16px;
  background: #fff;
  cursor: pointer;
  transition: all 0.3s;
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.process-card:hover {
  border-color: #409eff;
  box-shadow: 0 4px 12px rgba(64, 158, 255, 0.15);
  transform: translateY(-2px);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
}

.card-title {
  display: flex;
  align-items: center;
  gap: 8px;
  flex: 1;
}

.process-icon {
  font-size: 20px;
  color: #409eff;
}

.process-name {
  font-size: 16px;
  font-weight: 600;
  color: #303133;
  line-height: 1.4;
}

.card-content {
  flex: 1;
}

.process-description {
  margin: 0;
  font-size: 13px;
  color: #909399;
  line-height: 1.6;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
  text-overflow: ellipsis;
  min-height: 38px;
}

.card-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding-top: 12px;
  border-top: 1px solid #f0f2f5;
}

.footer-info {
  display: flex;
  gap: 16px;
}

.info-item {
  display: flex;
  align-items: center;
  gap: 4px;
  font-size: 12px;
  color: #909399;
}

.info-item i {
  font-size: 14px;
}

.footer-actions {
  display: flex;
  gap: 8px;
}

/* 空状态 */
.empty-category {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 60px 20px;
  color: #909399;
  background: #f5f7fa;
  border-radius: 8px;
  border: 2px dashed #dcdfe6;
}

.empty-category i {
  font-size: 64px;
  color: #c0c4cc;
  margin-bottom: 12px;
}

.empty-category p {
  margin: 0 0 16px 0;
  font-size: 14px;
}

/* 全局空状态 */
.global-empty {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 100px 20px;
  background: #fff;
  border-radius: 8px;
}

.global-empty i {
  font-size: 80px;
  color: #c0c4cc;
  margin-bottom: 20px;
}

.empty-title {
  margin: 0 0 8px 0;
  font-size: 18px;
  font-weight: 600;
  color: #606266;
}

.empty-description {
  margin: 0 0 24px 0;
  font-size: 14px;
  color: #909399;
}

/* 列表视图 */
.list-view {
  background: #fff;
  border-radius: 8px;
  padding: 20px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
}

/* 历史版本对话框样式 */
.loading-container {
  text-align: center;
  padding: 40px;
  color: #909399;
}

.loading-container i {
  font-size: 24px;
  margin-right: 8px;
}

.empty-history {
  text-align: center;
  padding: 40px;
  color: #909399;
}

.empty-history i {
  font-size: 48px;
  margin-bottom: 16px;
  display: block;
}

.history-content {
  padding: 0;
}

.history-header {
  margin-bottom: 20px;
  padding-bottom: 16px;
  border-bottom: 1px solid #e4e7ed;
}

.history-header h3 {
  margin: 0 0 8px 0;
  font-size: 18px;
  font-weight: 600;
  color: #303133;
}

.process-key {
  margin: 0;
  font-size: 14px;
  color: #909399;
}

/* 响应式 */
@media (max-width: 768px) {
  .toolbar {
    flex-direction: column;
    align-items: flex-start;
    gap: 16px;
  }
  
  .toolbar-left {
    flex-direction: column;
    align-items: flex-start;
  }
  
  .toolbar-right {
    width: 100%;
    flex-direction: column;
    gap: 12px;
  }
  
  .process-cards {
    grid-template-columns: 1fr;
  }
}
</style>

